import axios from 'axios'
import config from './config'
import Cookies from 'js-cookie'
import router from '@/router'
import store from '@/store'

export default function $axios (options) {
  return new Promise((resolve, reject) => {
    // 每个请求生成一个实例
    const instance = axios.create({
      baseURL: config.baseUrl,
      headers: config.headers,
      timeout: config.timeout,
      withCredentials: config.withCredentials
    })

    // 所有请求的前置处理（实例处理）
    instance.interceptors.request.use(
      config => {
        let token = Cookies.get('token')
        if (token) {
          config.headers.Authorization = 'Basic ' + token
        }
        return config
      },
      error => {
        // 请求错误时
        console.log('request:', error)
        // 1. 判断请求超时
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
          console.log('timeout请求超时')
        }
        const errorInfo = error.response
        console.log(errorInfo)
        if (errorInfo) {
          // 页面那边catch的时候就能拿到详细的错误信息,看最下边的Promise.reject
          error = errorInfo.data
          // 404 403 500 ...
          const errorStatus = errorInfo.status
          router.push({
            path: `/error/${errorStatus}`
          })
        }
        return Promise.reject(error) // 在调用的那边可以拿到(catch)你想返回的错误信息
      }
    )

    instance.interceptors.response.use(
      response => {
        let data
        // IE9时response.data(此处暂时用body，后期可改)是undefined，因此需要使用response.request.responseText(Stringify后的字符串)
        if (response.data === undefined) {
          data = JSON.parse(response.request.responseText)
        } else {
          data = response.data
        }
        // 返回的数据编码，统一处理
        switch (data.resultCode) {
          case 20001:
            store.state.app.menuRouteLoaded = false
            store.state.navTree = []
            sessionStorage.clear()
            Cookies.remove('token')
            router.push('/login')
            break;
          default:
        }
        return data
      },
      err => {
        if (err && err.response) {
          switch (err.response.status) {
            case 400:
              err.msg = '请求错误'
              break
            case 401:
              err.msg = '未授权，请登录'
              break
            case 403:
              err.msg = '拒绝访问'
              break
            case 404:
              err.msg = `请求地址出错: ${err.response.config.url}`
              break
            case 408:
              err.msg = '请求超时'
              break
            case 500:
              err.msg = '服务器内部错误'
              break
            case 501:
              err.msg = '服务未实现'
              break
            case 502:
              err.msg = '网关错误'
              break
            case 503:
              err.msg = '服务不可用'
              break
            case 504:
              err.msg = '网关超时'
              break
            case 505:
              err.msg = 'HTTP版本不受支持'
              break
            default:
          }
        }
        console.error(err)
        // 返回接口返回的错误信息
        return Promise.reject(err)
      }
    )
    // 请求处理
    instance(options).then(res => {
      resolve(res)
      return false
    }).catch(error => {
      reject(error)
    })
  })
}
